package com.electric.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.electric.common.CommonStringUtils;
import com.electric.common.LoggerInterface;
import com.electric.entity.User;
import com.electric.service.IUserService;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zhangbin
 * @since 2018-08-28
 */
@Controller
@RequestMapping("/user")
public class UserController implements LoggerInterface{
	@Autowired
	private IUserService userService;
	
	@RequestMapping("/login/{user}")
	public ModelAndView login(@PathVariable("user") String loginName, String password, HttpServletRequest request) {
		User user = userService.checkLoing(loginName, password);

		if (user != null) {
			request.getSession().setAttribute("loginUser", user);
			logger.debug("来自IP:" + CommonStringUtils.getIpAddress(request) + "的【" + request.getSession().getAttribute("loginUser") + "】用户登录成功。");
			return new ModelAndView("redirect:/index");
		} else {
			ModelAndView view = new ModelAndView("/index");

			view.addObject("loginError", true);
			return view;
		}
	}
	
	@RequestMapping("/login/")
	public ModelAndView login() {
		ModelAndView view = new ModelAndView("/index");

		view.addObject("loginError", true);
		return view;
	}
	
	@RequestMapping("/logout")
	public ModelAndView logout(HttpServletRequest request){
		ModelAndView view = new ModelAndView("/index");
		
		request.getSession().removeAttribute("loginUser");

		return view;
	}
}
